import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'

const id = 'tab'
const initTabActive = 'home'
const initTabs = () => [
  {
    title: '控制台',
    icon: 'House',
    name: initTabActive,
    // 'menu'-来源于菜单，'button'-来源页面按钮
    source: 'menu',
    // 当 source = button 的时候，所属菜单项的 name
    // 当 source = menu 的时候，保留空字符串或者undefined即可
    menu: '',
    query: {},
    params: {},
    closable: false
  }
]

const store = defineStore(
  id,
  () => {
    const router = useRouter()
    const tabActive = ref(initTabActive)
    const tabs = ref(initTabs())

    // 到某个 tab
    const toTab = ({ title, icon, name, source, menu, query, params, closable = true }) => {
      const index = tabs.value.findIndex((tab) => tab.name === name)

      if (index > -1) {
        tabs.value[index] = { title, icon, name, source, menu, query, params, closable }
        tabActive.value = name
        return
      }

      tabs.value.push({
        title,
        icon,
        name,
        source,
        menu,
        query,
        params,
        closable
      })

      tabActive.value = name
    }

    // 删除 tab
    const removeTab = (name) => {
      const index = tabs.value.findIndex((tab) => tab.name === name)
      if (index === -1) {
        return
      }

      if (tabActive.value === name) {
        const { menu } = tabs.value[index]
        tabActive.value = menu ? menu : tabs.value[index - 1].name
      }

      tabs.value.splice(index, 1)
    }

    // tabActive 修改，则路由需要变化
    watch(tabActive, (name) => {
      const tab = tabs.value.find((tab) => tab.name === name)
      if (tab) {
        // 保证每次 tab 切换都拉去最新的数据
        // 促使 :key="route.fullPath" 改变，这里将更新 query 即可
        // <RouterView v-slot="{ Component, route }">
        //   <KeepAlive>
        //     <component :is="Component" :key="route.fullPath" />
        //   </KeepAlive>
        // </RouterView>
        router.push({ name: tab.name, query: tab.query, params: tab.params })
      }
    })

    const $reset = () => {
      tabActive.value = initTabActive
      tabs.value = initTabs()
    }

    return { tabActive, tabs, toTab, removeTab, $reset }
  },
  {
    persist: {
      key: id
    }
  }
)

export default store
